package com.kws.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.core.domain.R;
import com.kws.system.api.domain.SysDept;
import com.kws.system.api.domain.SysRole;
import com.kws.system.domain.vo.*;
import com.kws.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.kws.common.core.utils.poi.ExcelUtil;
import com.kws.common.log.annotation.Log;
import com.kws.common.log.enums.BusinessType;
import com.kws.common.security.annotation.RequiresPermissions;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.domain.SysUserRole;
import com.kws.system.service.ISysDeptService;
import com.kws.system.service.ISysRoleService;
import com.kws.system.service.ISysUserService;

/**
 * 角色信息
 * 
 * @author zhangyh
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理模块")
public class SysRoleController
{
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private ISysMenuService iSysMenuService;

//    @RequiresPermissions("system:role:list")
    @GetMapping("/list")
    @ApiOperation("分页查询角色列表")
    public R<Page<SysRole>> list(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                @RequestParam(required = false) String roleName)
    {
        Page<SysRole> pageInfo = roleService.selectRoleListByName(pageNum,pageSize,roleName);
        return R.ok(pageInfo);
    }

    /**
     * 根据角色编号获取详细信息
     */
//    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/{roleId}")
    @ApiOperation("根据角色ID查询角色详情")
    public R getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return R.ok(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
//    @RequiresPermissions("system:role:add")
    @Log(title = "新增角色", businessType = BusinessType.INSERT)
    @ApiOperation("新增角色")
    @PostMapping("/add")
    public R add(@Validated @RequestBody CreateRoleRq rq)
    {
//        if (!roleService.checkRoleNameUnique(role))
//        {
//            return R.fail("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
//        }
//        else if (!roleService.checkRoleKeyUnique(role))
//        {
//            return R.fail("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
//        }
//        role.setCreateBy(SecurityUtils.getUsername());
        return roleService.createRole(rq);

    }

    /**
     * 修改保存角色
     */
//    @RequiresPermissions("system:role:edit")
    @Log(title = "修改角色", businessType = BusinessType.UPDATE)
    @ApiOperation("商家端-根据角色ID修改角色信息")
    @PostMapping("/update")
    public R edit(@Validated @RequestBody UpdateRoleRq rq)
    {
//        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
//        if (!roleService.checkRoleNameUnique(role))
//        {
//            return R.fail("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
//        }
//        else if (!roleService.checkRoleKeyUnique(role))
//        {
//            return R.fail("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
//        }
//        role.setUpdateBy(SecurityUtils.getUsername());
        return R.ok(roleService.updateRole(rq));
    }

    /**
     * 修改保存数据权限
     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
//    @ApiOperation("修改角色数据权限")
//    @PostMapping("/dataScope")
//    public R dataScope(@RequestBody SysRole role)
//    {
//        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
//        return R.ok(roleService.authDataScope(role));
//    }

    /**
     * 状态修改
     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
//    @ApiOperation("根据角色ID修改角色状态")
//    @PostMapping("/changeStatus")
//    public R changeStatus(@RequestBody SysRole role)
//    {
//        roleService.checkRoleAllowed(role);
//        roleService.checkRoleDataScope(role.getRoleId());
//        role.setUpdateBy(SecurityUtils.getUsername());
//        return R.ok(roleService.updateRoleStatus(role));
//    }

    /**
     * 删除角色
     */
//    @RequiresPermissions("system:role:remove")
    @Log(title = "删除角色", businessType = BusinessType.DELETE)
    @ApiOperation("根据角色ID删除角色")
    @GetMapping("/delete/{roleIds}")
    public R remove(@PathVariable Long[] roleIds)
    {
        return R.ok(roleService.deleteRoleByIds(roleIds));
    }


    @ApiOperation("根据角色ID添加用户")
    @Log(title = "添加角色用户", businessType = BusinessType.INSERT)
    @PostMapping("/add/userRole/byRoleId")
    public R addUserRoleByRoleId(@RequestBody AddUserRoleRq rq){
        return roleService.addUserRoleByRoleId(rq);
    }

    @ApiOperation("根据角色ID进行授权")
    @Log(title = "授权角色", businessType = BusinessType.GRANT)
    @PostMapping("/accredit/roleMenu")
    public R accreditRoleMenu(@RequestBody AccreditRoleMenuRq rq){
        return roleService.accreditRoleMenu(rq);
    }

    /**
     * 获取角色选择框列表
     */
//    @RequiresPermissions("system:role:query")
    @GetMapping("/optionselect")
    @ApiOperation("获取角色选择列表")
    public R optionselect()
    {
        return R.ok(roleService.selectRoleAll());
    }
    /**
     * 查询已分配用户角色列表
     */
//    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/allocatedList")
    @ApiOperation("查询用户已分配角色列表")
    public R allocatedList(SysUser user)
    {
        List<SysUser> list = userService.selectAllocatedList(user);
        return R.ok(list);
    }

    /**
     * 查询未分配用户角色列表
     */
//    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/unallocatedList")
    @ApiOperation("查询用户未分配角色列表")
    public R unallocatedList(SysUser user)
    {
        List<SysUser> list = userService.selectUnallocatedList(user);
        return R.ok(list);
    }

    /**
     * 取消授权用户
     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @ApiOperation("取消授权用户")
//    @PostMapping("/authUser/cancel")
//    public R cancelAuthUser(@RequestBody SysUserRole userRole)
//    {
//        return R.ok(roleService.deleteAuthUser(userRole));
//    }

    /**
     * 批量取消授权用户
     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @ApiOperation("批量取消用户授权")
//    @GetMapping("/authUser/cancelAll")
//    public R cancelAuthUserAll(@RequestParam(value = "roleId") Long roleId,@RequestParam(value = "userIds") Long[] userIds)
//    {
//        return R.ok(roleService.deleteAuthUsers(roleId, userIds));
//    }

    /**
     * 批量选择用户授权
     */
//    @RequiresPermissions("system:role:edit")
//    @Log(title = "角色管理", businessType = BusinessType.GRANT)
//    @ApiOperation("批量用户授权")
//    @GetMapping("/authUser/selectAll")
//    public R selectAuthUserAll(@RequestParam(value = "roleId") Long roleId,@RequestParam(value = "userIds") Long[] userIds)
//    {
//        roleService.checkRoleDataScope(roleId);
//        return R.ok(roleService.insertAuthUsers(roleId, userIds));
//    }

    @ApiOperation("商家端--根据角色ID授权菜单列表")
    @PostMapping("/accredit/menuById")
    public R accreditMenuById(@RequestBody CreateAccreditMenuRq rq){
        boolean status = roleService.accreditMenuById(rq);
        return R.ok(status);
    }

    /**
     * 获取对应角色部门树列表
     */
//    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/deptTree/{roleId}")
    @ApiOperation("根据角色ID获取对应角色部门树")
    public R deptTree(@PathVariable("roleId") Long roleId)
    {
        JSONObject resultJson = new JSONObject();
        resultJson.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        resultJson.put("depts", deptService.selectDeptTreeList(new SysDept()));
        return R.ok(resultJson);
    }

    @ApiOperation("根据角色ID查询未绑定用户列表")
    @GetMapping("/query/userRole/byRoleId")
    public R<List<SysUser>> queryUserRoleByRoleId(@RequestParam Long roleId){
        List<SysUser> userList = roleService.queryUserRoleByRoleId(roleId);
        return R.ok(userList);
    }

    @ApiOperation("商家端-获取当前商家角色")
    @PostMapping("/queryMerchantRolePage")
    public R<Page<SysRole>> queryMerchantRolePage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                              @RequestParam(required = false) String roleName){
        Page<SysRole> pageInfo = roleService.queryMerchantRolePage(pageNum,pageSize,roleName);
        return R.ok(pageInfo);
    }

    @Log(title = "商家端-新增角色", businessType = BusinessType.INSERT)
    @ApiOperation("商家端-新增角色")
    @PostMapping("/merchantAdd")
    public R merchantAdd(@Validated @RequestBody CreateMerchantRoleRq rq)
    {
        return R.ok(roleService.merchantAdd(rq));

    }
    @ApiOperation("商家端-根据菜单ID所有菜单-商家端1070，商家端app1072")
    @GetMapping(value = "/{menuId}")
    public R getMenuInfo(@PathVariable Long menuId)
    {
        return R.ok(iSysMenuService.selectMenuById(menuId));
    }

    @ApiOperation("商家端-角色启用禁用")
    @GetMapping(value = "updateStatus/{roleId}")
    public R updateStatus(@PathVariable Long roleId)
    {
        return R.ok(roleService.updateStatus(roleId));
    }

}
